﻿(function (jscript, undefined) {
    $.extend(jscript, {
        config: { req: -1, link: '', key: '' },
        store: null,
        ready: function (option) {
            var self = this;
            $.each(option, function (idx, item) {
                if (self.config.hasOwnProperty(idx)) {
                    self.config[idx] = item;
                }
            });
        },
        element: { elVue: new Vue({}), loading: null, loadingCount: 0 },
        mask: function (text) {
            var self = this;
            text = text || '请稍后...';
            if (!!ELEMENT) {
                if (self.element.loadingCount == 0) {
                    self.element.loading = ELEMENT.Loading.service({
                        lock: true,
                        body: true,
                        text: text,
                        spinner: 'el-icon-loading',
                        background: 'rgba(255,255,255,.5)'
                    });
                }
                Vue.nextTick(function () {
                    !!self.element.loading && self.element.loading.setText(text);
                });
                self.element.loadingCount++;
            }
        },
        unmask: function () {
            var self = this;
            if (!!ELEMENT) {
                Vue.nextTick(function () {
                    self.element.loadingCount--;
                    self.element.loadingCount = Math.max(self.element.loadingCount, 0);
                    if (self.element.loadingCount == 0) !!self.element.loading && self.element.loading.close();
                });
            }
        },
        postSuccess: function (res) {
            var self = this;
            if (res.code == -999) {
                self.msg(res.errmsg, function () {
                    window.top.location.replace(res.data.url);
                });
                return true;
            }
            return false;
        },
        postERR: function (msg) {
            var self = this;
            self.alert(msg, '未知错误');
        },
        // 询问框
        confirm: function (msg, yes, btn2, success) {
            var self = this;
            if (!!ELEMENT) {
                var box = ELEMENT.MessageBox.confirm(msg, '提示', {
                    title: '提示', message: msg, dangerouslyUseHTMLString: true, type: 'warning'
                    , closeOnClickModal: false, closeOnPressEscape: true, closeOnHashChange: true
                    , showCancelButton: true
                    , callback: function (action, ins) {
                        if ('confirm' === action) self.isFunction(yes) && yes.call(self);
                        else self.isFunction(btn2) && btn2.call(self);
                    }
                });
                if (self.isFunction(success)) {
                    success.call(self, box);
                }
            }
        },
        // 提示框
        msg: function (msg, fn, time, ic) {
            if (!msg) return;
            var self = this;
            if (!!ELEMENT) {
                ELEMENT.Message({
                    dangerouslyUseHTMLString: true,
                    message: msg,
                    duration: time || 3000,
                    type: ic || 'info',
                    onClose: function () {
                        self.isFunction(fn) && fn.call(self);
                    }
                });
            }
        },
        success: function (msg, fn, time) {
            var self = this;
            self.msg(msg, fn, time, 'success');
        },
        error: function (msg, fn, time) {
            var self = this;
            self.msg(msg, fn, time, 'error');
        },
        // 弹框
        alert: function (message, title, yes, success) {
            var self = this;
            if (!!ELEMENT) {
                var box = ELEMENT.MessageBox.alert(message, title || '提示', {
                    title: title || '提示', message: message, dangerouslyUseHTMLString: true, type: 'info'
                    , closeOnClickModal: false, closeOnPressEscape: false, closeOnHashChange: true
                    , showCancelButton: false
                    , callback: function (action, ins) {
                        self.isFunction(yes) && yes.call(self);
                    }
                });
                if (self.isFunction(success)) {
                    success.call(self, box);
                }
            }
        },
        // 加载层
        load: function (icon, time, shade) {
            var self = this;
            if (!!ELEMENT) {
                return ELEMENT.Loading.service({
                    lock: true,
                    body: true,
                    text: '',
                    spinner: icon || 'el-icon-loading',
                    background: shade || 'rgba(255,255,255,.5)'
                });
            }
            return undefined;
        },
        hideload: function (load) {
            var self = this;
            if (!!ELEMENT && !!load && self.isFunction(load.close)) {
                load.close();
            }
        },
        emptyComponent: function (text) {
            return '<el-empty description="' + text + '"></el-empty>'
        },
        /**
         * 公共 验证element表单，验证不通过滚动到第一个错误
         * @param {Vue} vue vue实例
         * @param {String} formName el-form的ref
         * @param {Function} success 验证通过执行的函数
         */
        validateElForm: function (vue, formName, success, fail) {
            var self = this, form = !!vue && !!formName && !!vue.$refs ? vue.$refs[formName] : null;
            if (!form || !self.isFunction(form.validate)) return;
            form.validate(function (valid, object) {
                if (!valid) {
                    var error = null;
                    $.each(object, function (k, v) {
                        if (self.isArray(v) && v.length > 0 && !!v[0]) {
                            error = v[0].message;
                            if (!!error) return false;
                        }
                    });
                    error = '验证有误' + (!!error ? '【' + error + '】' : '') + '，请检查输入是否正确。';
                    vue.$nextTick(function () {
                        var el = document.getElementsByClassName('is-error');
                        self.scrollIntoView(el);
                    });
                    if (self.isFunction(fail)) fail.call(self, error);
                    else self.isFunction(success) && self.error(error);
                    return false;
                }
                self.isFunction(success) && success.call(self);
            });
        },
        /**
         * 公共vxe-table验证
         * @param {any} options
         */
        validVXETable: function (options) {
            var self = this
                , o = {
                    table: !!options && !!options.table && self.isFunction(options.table.validate) ? options.table : null, //vxt-table实例
                    success: !!options && self.isFunction(options.success) ? options.success : function () { }, //验证成功执行的回调
                    fail: !!options && self.isFunction(options.fail) ? options.fail : function (err) { self.error(err); } //验证失败执行的回调
                };

            if (!o.table) {
                return o.fail('要验证的数据表为空');
            }
            var msgList = [];
            o.table.validate(true, function (errMap) {
                if (!!errMap) {
                    $.each(errMap, function (key, val) {
                        $.each(val, function (ix0, params) {
                            $.each(params.rules, function (ix1, rule) {
                                msgList.push('第 {0} 行 {1} 校验错误：{2}'.formatStr(params.rowIndex + 1, params.column.title, rule.message))
                            });
                        });
                    });
                    o.fail.call(self, msgList.join('<br/>'));
                }
                else {
                    o.success.call(self);
                }
            });
        },
        fileCover: function () {
            var self = this;
            return {
                template: '<label class="flex-column" style="vertical-align:middle;align-items:center;justify-content:center;overflow:hidden;position:relative;cursor: pointer;user-select:none;"><el-upload ref="file" multiple :auto-upload="false" :show-file-list="false" :accept = "accept" :on-change="selectFile" :disabled = "disabled" style = "position: absolute; left: 0; top: 0; right: 0; bottom: 0; opacity: 0; cursor: pointer; user-select: none; display:none;"></el-upload><div><slot></slot></div></label > ',
                props: {
                    accept: {
                        type: String,
                        default: ''
                    },
                    size: {
                        type: Number,
                        default: 209715200 //200M
                    },
                    disabled: {
                        type: Boolean,
                        default: false
                    },
                },
                methods: {
                    selectFile: function (e,e1) {
                        var _this = this, file = e.raw;
                        if (file.size > _this.size) return self.error('文件最大不可超过' + self.getFileSize(_this.size));
                        _this.$emit('change', file);
                    },
                    clickFile: function(e){
                        var _this = this;
                        console.log(e)
                        _this.$emit('click');
                    },
                    fileBlur: function (e) {
                        console.log(e)
                    }
                }
            };
        },
        /**
         * 生成二维码
         * */
        qrcode: function () {
            var self = this;
            return {
                template: '<img :src="qrcode" />',
                props: {
                    value: {
                        type: String,
                        default: ''
                    },
                    width: {
                        type: Number,
                        default: 200
                    }
                },
                data: function () {
                    return {
                        qrcode: null
                    };
                },
                watch: {
                    value: function (val) {
                        this.setCode(val);
                    }
                },
                created: function () {

                },
                mounted: function () {
                    this.setCode(this.value);
                },
                methods: {
                    setCode: function (val) {
                        var _this = this;
                        QRCode.toDataURL(val, {
                            errorCorrectionLevel: 'M',
                            width: _this.width,
                            margin: 2,
                            color: { dark: '#000000', light: '#ffffff' }
                        }, function (err, url) {
                            _this.qrcode = url;
                        });
                    }
                }
            };
        },
        remoteScript: function () {
            return {
                render: function (createElement) {
                    var self = this;
                    return createElement('script', {
                        attrs: {
                            type: 'text/javascript',
                            src: self.src
                        },
                        on: {
                            load: function (event) {
                                self.$emit('load', event);
                            },
                            error: function (event) {
                                self.$emit('error', event);
                            },
                            readystatechange: function (event) {
                                if (this.readyState == 'complete') {
                                    self.$emit('load', event);
                                }
                            }
                        }
                    });
                },
                data: function () {
                    return {

                    };
                },
                props: {
                    src: {
                        type: String,
                        required: true
                    }
                }
            };
        },
        remoteStyle: function () {
            return {
                render: function (createElement) {
                    var self = this;
                    return createElement('link', {
                        attrs: {
                            rel: 'stylesheet',
                            type: 'text/css',
                            href: self.src
                        },
                        on: {
                            load: function (event) {
                                self.$emit('load', event);
                            },
                            error: function (event) {
                                self.$emit('error', event);
                            },
                            readystatechange: function (event) {
                                if (this.readyState == 'complete') {
                                    self.$emit('load', event);
                                }
                            }
                        }
                    });
                },
                props: {
                    src: {
                        type: String,
                        required: true
                    }
                }
            };
        },
        aliveScroll: function (vm, ref, isAdd) {
            var self = this, ref = '' + ref;
            if (!vm instanceof Vue || !vm.$refs[ref]) return;
            if (!vm.aliveScroll || !self.isObject(vm.aliveScroll)) {
                console.warn('missing aliveScroll');
                return;
            }

            var add = 0;
            if (isAdd === true) add = 1;
            else if (isAdd === false) add = 2;
            else {
                var stack = $.trim((new Error()).stack);
                var caller = $.trim(stack.split("\n")[2]).split(" ")[1];
                if (!caller) caller = stack;
                if (!caller) {
                    try {
                        throw new Error();
                    }
                    catch (e) {
                        caller = $.trim(e.stack);
                    }
                }
                add = caller.indexOf('mounted') > -1 ? 1 : caller.indexOf('activated') > -1 ? 2 : 0;
            }

            var el = vm.$refs[ref], top = '__' + ref + '__scrollTop', left = '__' + ref + '__scrollLeft';
            var bodyWrapper = el.bodyWrapper;
            if (!!bodyWrapper) {
                if (add == 1) {
                    vm.$set(vm.aliveScroll, top, 0);
                    vm.$set(vm.aliveScroll, left, 0);
                    $(bodyWrapper).off('scroll').on('scroll', function (e) {
                        vm.$set(vm.aliveScroll, top, bodyWrapper.scrollTop);
                        vm.$set(vm.aliveScroll, left, bodyWrapper.scrollLeft);
                    });
                }
                else if (add == 2) {
                    vm.$nextTick(function () {
                        !!el && !!el.doLayout && el.doLayout();
                        vm.$nextTick(function () {
                            bodyWrapper.scrollTop = vm.aliveScroll[top];
                            bodyWrapper.scrollLeft = vm.aliveScroll[left];
                        });
                    });
                }
            }
            else {
                if (add == 1) {
                    vm.$set(vm.aliveScroll, top, 0);
                    vm.$set(vm.aliveScroll, left, 0);
                    $(el).off('scroll').on('scroll', function (e) {
                        vm.$set(vm.aliveScroll, top, $(el).scrollTop());
                        vm.$set(vm.aliveScroll, left, $(el).scrollLeft());
                    });
                }
                else if (add == 2) {
                    vm.$nextTick(function () {
                        vm.$nextTick(function () {
                            $(el).scrollTop(vm.aliveScroll[top]);
                            $(el).scrollLeft(vm.aliveScroll[left]);
                        });
                    });
                }
            }
        }
    });
    //指令 v-blur 使 el-button 点击后失去焦点
    Vue.use({
        install: function (app) {
            var fun = function (e) {
                var target = e.target;
                if (target.nodeName == "SPAN" || target.nodeName == "I") {
                    target = e.target.parentNode;
                }
                target.blur();
            };
            app.directive('blur', {
                inserted: function (el) {
                    el.addEventListener('click', fun, true);
                },
                unbind: function (el) {
                    el.removeEventListener('click', fun)
                }
            });
        }
    });

    Vue.directive('removeAriaHidden', {
        bind: function (el, binding) {
            var ariaEls = el.querySelectorAll('.el-radio__original');
            ariaEls.forEach(function (item) {
                item.removeAttribute('aria-hidden');
            });
        }
    });
})(window.$jscript.fn);